package com.allianz.webapps.controllers;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.allianz.frame.utils.ApplicationContextUtil;
import com.allianz.frame.utils.StringUtil;
import com.allianz.webapps.https.interfaces.type001.CoverInit;
import com.allianz.webapps.https.interfaces.type001.pojo.User;
import com.allianz.webapps.https.interfaces.util.HttpsUtil;
import com.allianz.webapps.https.interfaces.util.ObjectUtil;
import com.allianz.webapps.orderspojo.AppBase;
import com.allianz.webapps.orderspojo.CP;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Controller
@RequestMapping(value="main")
public class AppInitSignController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private ObjectUtil objectUtil;
	
	@RequestMapping(value="initSign")
	@ResponseBody
	public String initSign(@RequestParam(value="jsonParam") String jsonParam,HttpServletRequest request,HttpServletResponse response)
			throws Exception{
		AppBase appBase=objectMapper.readValue(jsonParam, AppBase.class);
		String body=objectUtil.requestParam(appBase, "app.initSign");
		return body;
	}
	
	@RequestMapping(value="appGetCP")
	@ResponseBody
	public Map<String,Object> appGetCP(@RequestParam(value="jsonParam") String jsonParam,HttpServletRequest request,HttpServletResponse response)
			throws Exception{
		
		JSONObject cpJson=JSONObject.fromObject(jsonParam);
		HashMap<String,Object> map = new HashMap<String,Object>();
		CP cpObject = (CP) JSONObject.toBean(cpJson,CP.class );
		User u = (User) ApplicationContextUtil.getSession("username");	
		cpObject.getAppBase().setUser(u);
		logger.info(cpObject!=null?cpObject.toString():"cpObject is null");
		String requestLoginParam = CoverInit.requestLoginParam(cpObject);
		logger.info(requestLoginParam);
		String body = HttpsUtil.httpsPost(requestLoginParam);
		JSONObject json = JSONObject.fromObject(body);
		map.put("data", json.get("Body"));
		return map;
	}
}
